<?php

namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller
{
    /*定义学校类别数组*/
    protected $school_list = ['1' => '清华', '2' => '北大', '3' => '湖大', '4' => '人民大学', '5' => '杭州大学', '6' => '湖南电大', '7' => '中国人民银行'];
    /*定义爱好数组*/
    protected $hobby_list = ['1' => '爱好1', '2' => '爱好2', '3' => '爱好3', '4' => '爱好4', '5' => '爱好5'];
    /*学生信息列表*/
    public function index()
    {
        /*查询条件*/
        $map['status'] = 1;
        /*搜序*/
        $search_name = I('search_name');
        if ($search_name) {
            $map['name'] = array('like', '%' . $search_name . '%');
            $this->assign('search_name', $search_name);
        }
        /*调用模型*/
        $User = D('User');
        $list = $User->getPages($map);

        foreach ($list['list'] as $k => $v) {
            $list['list'][$k]['school_id'] = $this->school_list[$v['school_id']];
            if ($v['hobby']) {
                /*用逗号, 把字符串分隔成数组*/
                $hobby = explode(',', $v['hobby']);
                $hobby_str = '';
                foreach ($hobby as $v2) {
                    $hobby_str .= $this->hobby_list[$v2] . ',';
                }
                /*去掉结尾逗号*/
                $list['list'][$k]['hobby'] = rtrim($hobby_str, ',');
            }
            /**将照片进行分割 */
            if ($v['head_img']) {
                $head_imgMain = explode('#', $v['head_img']);
                if (sizeof($head_imgMain) > 1) {
                    array_shift($head_imgMain);
                    /**删除数组的第一个元素*/
                    $t = [];
                    for ($i = 0; $i < sizeof($head_imgMain); $i++) {
                        $head_imgThumb = explode(',', $head_imgMain[$i]);
                        /*/Uploads/img/20210108/5ff7b22936e34.png,/Uploads/img/20210108/thumb_5ff7b22936e34.png */
                        /**将$head_imgThumb 
                         * Array ( 
                         * [0] => /Uploads/img/20210108/5ff7b22936e34.png 
                         * [1] => /Uploads/img/20210108/thumb_5ff7b22936e34.png )
                         * 中的第二个数值放入 $head_imgMain数组进行改写 */
                        $t[$i] = $head_imgThumb[1];
                    };
                    $v['head_img'] = $t;
                } else {
                    $v['head_img'] = $head_imgMain;
                }
            }
            $list['list'][$k]['head_img'] = $v['head_img'];/*将转换好的url数组再次赋值*/
            /*性别转换成文字形式*/
            $list['list'][$k]['sex'] = $v['sex'] ? '男' : '女';
            /*时间戳转日期格式*/
            $list['list'][$k]['admission_time'] = date('Y-m-d', $v['admission_time']);
        }
        $this->assign('list', $list);
        $this->display();
    }
    /*新增/编辑*/
    public function edit()
    {
        /*调用模型*/
        $User = D('User');
        if (IS_POST) {
            /*接收post传过来的所有数据*/
            $data = I('post.');
            /*接收上传的照片文件*/
            $file = $_FILES;
            if (!empty($file['head_img']['name'])) {
                $upload = new \Think\Upload(); // 实例化上传类
                $upload->maxSize   =     3145728; // 设置附件上传大小
                $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
                $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
                $upload->savePath  =     ''; // 设置附件上传（子）目录
                // 上传文件
                $info   =   $upload->upload();
                if (!$info) { // 上传错误提示错误信息
                    $this->error($upload->getError());
                    exit;
                } else { // 上传成功
                    /*拼接图片地址*/
                    $data['head_img'] = ltrim($upload->rootPath, '.') . $info["head_img"]['savepath'] . $info["head_img"]['savename'];
                }
            }
            if ($data['hobby']) {
                /*把数组变成用逗号,分隔的字符串*/
                $data['hobby'] = implode(',', $data['hobby']);
            }
            $data['create_time'] = time();
            $res = $User->update($data);
            if ($res) { /*操作成功 跳转到index*/
                $this->success('操作成功', U('index'));
                exit;
            } else {
                $this->error('操作失败,' . $User->getError());
                exit;
            }
        }
        $id = I('id');
        //更新部分数据获取
        if ($id) {
            $map['id'] = $id;
            $info = $User->getFind($map);
            $info['hobby'] = explode(',', $info['hobby']);
            /**将照片进行分割 */
            if ($info['head_img']) {
                $head_imgMain = explode('#', $info['head_img']);
                if (sizeof($head_imgMain) > 1) {
                    array_shift($head_imgMain);/**删除数组的第一个元素*/
                    $t = [];
                    for ($i = 0; $i < sizeof($head_imgMain); $i++) {
                        $head_imgThumb = explode(',', $head_imgMain[$i]);
                        /*/Uploads/img/20210108/5ff7b22936e34.png,/Uploads/img/20210108/thumb_5ff7b22936e34.png */
                        /**将$head_imgThumb 
                         * Array ( 
                         * [0] => /Uploads/img/20210108/5ff7b22936e34.png 
                         * [1] => /Uploads/img/20210108/thumb_5ff7b22936e34.png )
                         * 中的第二个数值放入 $head_imgMain数组进行改写 */
                        $t[$i] = $head_imgThumb[1];
                    };
                    $info['head_img'] = $t;
                } else {
                    $info['head_img'] = $head_imgMain;
                }
            };
            $this->assign('head_img_list',$info['head_img']);
            $this->assign('info', $info);
        }
        $this->assign('school_list', $this->school_list);
        $this->assign('hobby_list', $this->hobby_list);
        $this->display();
    }
    /*删除图片*/
    public function ajaxDelImg()
    {
        if (IS_POST) {
            $id = I('id');
            if ($id) {
                $map['id'] = $id;
                $User = D('User');
                $info = $User->getFind($map);
                $img = '.' . $info['head_img'];
                /*数据库删除图片地址*/
                $info['head_img'] = '';
                $res = $User->update($info);
                if ($res) {
                    /*服务器上删除图片*/
                    unlink($img);
                    $data['status'] = 1;
                    $data['msg'] = '删除成功';
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '删除失败';
                }
            } else {
                $data['status'] = 0;
                $data['msg'] = '参数错误';
            }
        } else {
            $data['status'] = 0;
            $data['msg'] = '非法操作';
        }
        $this->ajaxReturn($data);
    }

    /*删除信息*/
    public function setStatus()
    {
        $ids = I('ids');
        $status = I('status', '-1');
        if ($ids) {
            /*删除条件*/
            $map['id'] = array('in', $ids);
            /*调用模型*/
            $User = D('User');
            $update_data['status'] = $status;
            $update_data['delete_time'] = time();
            $res = $User->del($map, $update_data);
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('参数错误');
        }
    }

    public function upload()
    {
        $dir = empty(I('get.dir')) ? 'Uploads/img/' : 'Uploads/' . I('get.dir') . '/';
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $config = array(
            'maxSize' => 2 * 1024 * 1024,
            'rootPath' => './',
            'savePath' => $dir,
            'saveName' => array('uniqid', ''),
            'exts' => array('jpg', 'gif', 'png', 'jpeg'),
            'autoSub' => true,
            'subName' => array('date', 'Ymd'),
        );

        $upload = new \Think\Upload($config); // 实例化上传类 
        $info = $upload->upload();
        if ($info) {
            $image_path = '';
            $thumb_image = '';
            foreach ($info as $v) {
                $image_path = $v['savepath'] . $v['savename']; //生成缩略图
                $img = $v['savepath'] . $v['savename']; //获取文件上传目录
                $image = new \Think\Image();
                $image->open($img);  //打开上传图片
                $thumb_image = $v['savepath'] . 'thumb_' . $v['savename'];
                $image->thumb(300, 300, \Think\Image::IMAGE_THUMB_SCALE)->save($thumb_image); //生成等比缩略图
            }
            $res = [
                'type' => 1,
                'msg' => 'success',
                'image_path' => $image_path,
                'thumb_image' => $thumb_image,
            ];
            $this->ajaxReturn($res, 'json');
        } else {
            $res = [
                'type' => 2,
                'msg' => $upload->getError()
            ];
            $this->ajaxReturn($res, 'json');
        }
    }
}
